package server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolConfig;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

public class ServerBootstarp {

    public static void main(String[] args) throws InterruptedException {
        final EventLoopGroup bossGroup = new NioEventLoopGroup();
        final EventLoopGroup workerGroup = new NioEventLoopGroup();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                workerGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            }
        });
        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                         .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                     ChannelPipeline p = ch.pipeline();
                        p.addLast("httpServerCodec", new HttpServerCodec());
                        p.addLast("httpObjectAggregator", new HttpObjectAggregator(65536));
                        p.addLast("test1", new MyTestDecoder1());//解析回复http

                     //   p.addLast("MqttWebSocketCodec",new MqttWebSocketCodec());
                        p.addLast("MyWebSocketHandler",new MyWebSocketHandler());
                        p.addLast("mqttDecoder", new MqttDecoder());
                        p.addLast("mqttEncoder", MqttEncoder.INSTANCE);

                        p.addLast("myHandler", new BrokerHandler(65535));

                                     }
        })
                .option(ChannelOption.SO_BACKLOG, 511)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(1883).sync();
        f.channel().closeFuture().sync();
    }

}
